using System.Collections.Generic;
using Game.Main.Model;
using UnityEngine;

namespace Game.Component
{
	public class TestTubeItem : CupItem
	{
		private float angleDif;

		private List<TestTubeItem> targetItems = new List<TestTubeItem>();

		private TestTubeItem targetItem;

		private int selectIndex;

		private float minDis;

		private float tempDis;

		public override void Init(ItemArchiveData data)
		{
			base.Init(data);
		}

		protected override void LatedUpdateFill()
		{
			if (rotateAnimType == RotateAnimType.Static && curAngle != targetAngle)
			{
				angleDif = Mathf.Abs(curAngle - targetAngle);
				if (((!(angleDif > 180f)) ? angleDif : Mathf.Abs(angleDif - 360f)) < 0.4f)
				{
					curAngle = targetAngle;
					rotateAnimType = RotateAnimType.Static;
				}
				else
				{
					curAngle = Mathf.LerpAngle(curAngle, targetAngle, Time.deltaTime * 10f);
				}
				SetLocalRotation(new Vector3(0f, 0f, curAngle));
			}
			if (fillAmount > 0f)
			{
				targetItem = GetTargetItem();
				if (targetItem != null)
				{
					MinusFill(Time.deltaTime / 2f);
					targetItem.AddFill(Time.deltaTime / 2f);
					targetItem.UpdateMixColor(waterSprite.color);
					if (targetItem.fillAmount >= 1f)
					{
						RemoveTarget(targetItem);
					}
					if (fillAmount <= 0f)
					{
						fillAmount = 0f;
						targetAngle = 0f;
					}
					return;
				}
			}
			base.LatedUpdateFill();
		}

		private TestTubeItem GetTargetItem()
		{
			if (targetItems.Count > 0)
			{
				selectIndex = -1;
				minDis = float.MaxValue;
				for (int i = 0; i < targetItems.Count; i++)
				{
					TestTubeItem testTubeItem = targetItems[i];
					if (!(testTubeItem == null) && !(testTubeItem.transform.position.x > base.transform.position.x))
					{
						tempDis = Vector2.Distance(base.transform.position, testTubeItem.transform.position);
						if (tempDis < minDis)
						{
							minDis = tempDis;
							selectIndex = i;
						}
					}
				}
				if (selectIndex != -1)
				{
					return targetItems[selectIndex];
				}
			}
			return null;
		}

		protected override void OnItemTriggerEnter(ColliderData collData)
		{
			base.OnItemTriggerEnter(collData);
			if (collData.item != null && collData.item.itemData.scriptType == 135 && ((TestTubeItem)collData.item).fillAmount < 1f && fillAmount > 0f)
			{
				targetAngle = 45f;
				if (!targetItems.Contains((TestTubeItem)collData.item))
				{
					targetItems.Add((TestTubeItem)collData.item);
				}
			}
		}

		protected override void OnItemTriggerExit(ColliderData collData)
		{
			base.OnItemTriggerExit(collData);
			RemoveTarget(collData.item);
		}

		private void RemoveTarget(BaseItem item)
		{
			if (item != null && item.itemData.scriptType == 135)
			{
				targetItems.Remove((TestTubeItem)item);
				if (targetItems.Count <= 0)
				{
					targetAngle = 0f;
				}
			}
		}

		public override void TouchUp(TouchEventData touchEventData)
		{
			base.TouchUp(touchEventData);
			targetItems.Clear();
		}
	}
}
